/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.teamx.parking.slice;

import com.alibaba.fastjson.JSONObject;
import com.socks.library.KLog;
import com.teamx.parking.bean.NetConfigInfo;
import com.teamx.parking.ResourceTable;
import com.xuhao.didi.core.iocore.interfaces.IPulseSendable;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.client.sdk.client.connection.NoneReconnect;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.wifi.WifiDevice;
import org.apache.commons.lang3.StringUtils;

import javax.lang.model.element.Element;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    private static final int REQUEST_CODE = 1; // Any positive integer.
    private static final String DEVICE_SERVER_IP = "192.168.5.1";
    private static final int DEVICE_SERVER_PORT = 8686;
    private TextField tfSsid;
    private TextField tfPassword;
    private int doorIndex = 0; // A/B/C/D 门
    private int doorTypeIndex = 0; // 入口/出口

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_net_config);
        initComponents();
    }

    /**
     * socket长连接使用方法
     */
    private void initSocket() {
        EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());
        ConnectionInfo mInfo = new ConnectionInfo(DEVICE_SERVER_IP, DEVICE_SERVER_PORT);
        OkSocketOptions mOkOptions = new OkSocketOptions.Builder()
                .setReconnectionManager(new NoneReconnect())
                .setConnectTimeoutSecond(3)
                .setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
                    @Override
                    public void handleCallbackEvent(ActionDispatcher.ActionRunnable runnable) {
                        mHandler.postTask(runnable);
                    }
                })
                .build();
        IConnectionManager mManager = OkSocket.open(mInfo).option(mOkOptions);

        SocketActionAdapter adapter = new SocketActionAdapter() {
            @Override
            public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
                KLog.i("onSocketConnectionSuccess:" + action);
                //成功
                NetConfigInfo netConfigInfo = new NetConfigInfo(tfSsid.getText(), tfPassword.getText(), getGroupData());
                mManager.send(netConfigInfo);
                KLog.i(netConfigInfo);
            }

            @Override
            public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
                // 断开
                KLog.i(action);
            }

            @Override
            public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
                //连接失败
                KLog.i(action);
                mManager.disconnect();
            }

            @Override
            public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
                //从服务器读取到字节回调
                mManager.disconnect();
                KLog.i(action);
                JSONObject respond = (JSONObject) JSONObject.parse(data.getBodyBytes());
            }

            @Override
            public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
                //写给服务器字节后回调
                KLog.i(action);
            }

            @Override
            public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
                //发送心跳后的回调
                KLog.i(info);
            }

        };
        mManager.registerReceiver(adapter);
        mManager.connect(); //连接
    }

    private void showSuccessDialog() {
        CommonDialog commonDialog = new CommonDialog(getContext());
        commonDialog.setSize(AttrHelper.vp2px(300, this), AttrHelper.vp2px(150, this));
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setCornerRadius(AttrHelper.vp2px(15, this));
        Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_dialog_success,
                null, false);
        commonDialog.setContentCustomComponent(container);
        commonDialog.setAutoClosable(true);
        commonDialog.show();
    }


    private void initComponents() {
        //dialog
        CommonDialog commonDialog = new CommonDialog(getContext());
        commonDialog.setSize(AttrHelper.vp2px(300, this), AttrHelper.vp2px(150, this));
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setCornerRadius(AttrHelper.vp2px(15, this));
        Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_dialog,
                null, false);
        container.findComponentById(ResourceTable.Id_dialog_btn).setClickedListener(component -> {
            // 跳转设置
            Intent intent = new Intent();
            Operation operation =
                    new Intent.OperationBuilder()
                            .withBundleName("com.android.settings")
                            .withAbilityName("com.android.settings.Settings$WifiSettingsActivity")
                            .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                            .build();
            intent.setOperation(operation);
            startAbility(intent);
            commonDialog.hide();
        });
        commonDialog.setContentCustomComponent(container);
        commonDialog.setAutoClosable(true);
        commonDialog.show();

        findComponentById(ResourceTable.Id_net_text_other_network).setClickedListener(component -> {
            presentForResult(new OtherWifiSlice(), new Intent(), REQUEST_CODE);
        });
        tfSsid = (TextField) findComponentById(ResourceTable.Id_net_tf_ssid);
        tfPassword = (TextField) findComponentById(ResourceTable.Id_net_tf_password);

        findComponentById(ResourceTable.Id_net_button_ok).setClickedListener(component -> {
            initSocket();
            getGroupData();
            showSuccessDialog();
        });
        findComponentById(ResourceTable.Id_net_button_qrcode).setClickedListener(component -> {
            Intent intent = new Intent();
            intent.setParam("ssid", tfSsid.getText());
            intent.setParam("password", tfPassword.getText());
            intent.setParam("group", getGroupData());
            present(new QRCodeSlice(), intent);
        });
        // 门口选择
        DirectionalLayout doorLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_door);
        setButtonStyle(doorLayout.getComponentAt(doorIndex), true);
        int doorCount = doorLayout.getChildCount();
        for (int i = 0; i < doorCount; i++) {
            int finalI = i;
            doorLayout.getComponentAt(i).setClickedListener(component -> {
                if (finalI != doorIndex) {
                    setButtonStyle(doorLayout.getComponentAt(doorIndex), false);
                    setButtonStyle(doorLayout.getComponentAt(finalI), true);
                    doorIndex = finalI;
                }
            });
        }

        // 前后门
        Button entrance = (Button) findComponentById(ResourceTable.Id_btn_entrance);
        setButtonStyle(entrance, true);
        Button exit = (Button) findComponentById(ResourceTable.Id_btn_exit);
        entrance.setClickedListener(component -> {
            setButtonStyle(component, true);
            setButtonStyle(exit, false);
            doorTypeIndex = 0;
        });
        exit.setClickedListener(component -> {
            setButtonStyle(component, true);
            setButtonStyle(entrance, false);
            doorTypeIndex = 1;
        });
    }

    private String getGroupData() {
        List doorList = Arrays.asList("A", "B", "C", "D");
        List doorTypeList = Arrays.asList("ENTRANCE", "EXIT");
        String res = doorList.get(doorIndex) + "_" + doorTypeList.get(doorTypeIndex);
        return res;
    }

    private void setButtonStyle(Component component, boolean isSetBorder) {
        ShapeElement shapeElement = new ShapeElement();
        if (isSetBorder) {
            shapeElement.setStroke(3, RgbColor.fromArgbInt(Color.rgb(255, 255, 255)));
        }
        shapeElement.setCornerRadius(AttrHelper.vp2px(18, getContext()));
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.rgb(93, 103, 133)));
        component.setBackground(shapeElement);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    /**
     * otherWifi页面回调结果
     */
    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        KLog.i("onResult onResult==");
        switch (requestCode) {
            case REQUEST_CODE: {
                String resultSsid = resultIntent.getStringParam("ssid");
                if (!StringUtils.isEmpty(resultSsid)) {
                    tfSsid.setText(resultSsid);
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
